package com.atguigu.spzx.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.SPZXException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.constant.CacheConstant;
import com.atguigu.spzx.mapper.SysUserMapper;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysRole;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import com.atguigu.spzx.service.SysUserService;
import com.atguigu.spzx.service.ValidateCodeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;


    // @Resource(type = RedisTemplate.class)
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //获取用户信息
    @Override
    public Map<String, String> getUserInfo(String token) {
        //   String s = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_PREFIX + token);
        //    SysUser sysUser = JSON.parseObject(s, SysUser.class);
        SysUser sysUser = (SysUser) AuthContextUtil.get();
        Map<String, String> map = new HashMap<>();
        map.put("avatar", sysUser.getAvatar());
        map.put("name", sysUser.getName());
        return map;

    }

    //等出
    @Override
    public void logout(String token) {
        redisTemplate.delete(CacheConstant.USER_LOGIN_PREFIX + token);
    }

    //查询用户信息
    @Override
    public PageInfo<SysUser> findPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<SysUser> page = sysUserMapper.findByPage(sysUserDto);


        return new PageInfo<>(page);
    }



    @Override
    public void removeById(Long id) {
        sysUserMapper.removeById(id);
    }

    @Override
    public SysUser findByUsername(SysUser sysUser) {
        SysUser byUsername = sysUserMapper.findByUsername(sysUser);
        return byUsername;
    }

    @Override
    public void updateUser(SysUser sysUser) {
        sysUserMapper.updateUser(sysUser);
    }

    //插入用户信息
    @Override
    public void saveUser(SysUser sysUser) {


        //加密
        String password = sysUser.getPassword();
        String passwordByMD5 = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(passwordByMD5);
        sysUserMapper.saveUser(sysUser);
    }

    //登入
    @Override
    public LoginVo login(LoginDto loginDto) {

        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        //验证验证码
        String validateCaptcha = redisTemplate.opsForValue().get(CacheConstant.USER_LOGIN_VALIDATECODE_PREFIX + codeKey);
        if (StrUtil.isEmpty(validateCaptcha)) {
            throw new SPZXException(ResultCodeEnum.CAPTCHA_PAST);
        } else if (!StrUtil.equalsIgnoreCase(captcha, validateCaptcha)) {
            throw new SPZXException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        //StrUtil 帮忙封装了字符串检验操作
        if (StrUtil.isEmpty(userName) || StrUtil.isEmpty(password)) {
            throw new SPZXException(ResultCodeEnum.LOGIN_ERROR);
        }


        //获得密码
        SysUser sysUser = sysUserMapper.getSysUserByUsername(userName);
        String passwordMd5 = sysUser.getPassword();
        //加密验证
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!s.equals(passwordMd5)) {
            throw new SPZXException(ResultCodeEnum.LOGIN_ERROR);
        }

        Integer status = sysUser.getStatus();
        if (status == 0) {
            throw new SPZXException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //token
        String token = UUID.randomUUID().toString().replace("-", "");
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token(token);
        //TODO 临时更改代码
        //redis springboot下的redis 同时要写配置文件
        //redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_PREFIX + token, JSON.toJSONString(sysUser), 30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(CacheConstant.USER_LOGIN_PREFIX + token, JSON.toJSONString(sysUser));
        return loginVo;
    }
}
